package cn.alusiaor.eurekaclientarticleservice.exception;


import cn.alusiaor.eurekaclientarticleservice.response.CommonResult;
import feign.codec.DecodeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author ruoyi
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(CustomException.class)
    public CommonResult<Void> handleCustomException(CustomException e) {
        log.error("业务异常", e);
        CommonResult<Void> commonResult = new CommonResult<>(e);
        return commonResult;
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public CommonResult<Void> handleException(Exception e) {
        log.error("服务异常", e);
        CommonResult<Void> commonResult = new CommonResult<>("服务异常", e);
        return commonResult;
    }

    /**
     * 自定义验证异常
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BindException.class)
    public CommonResult<Void> validatedBindException(BindException e) {
        log.error("参数错误", e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        CommonResult<Void> commonResult = new CommonResult<>(message, e);
        return commonResult;
    }

    /**
     * 自定义验证异常
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult<Void> validExceptionHandler(MethodArgumentNotValidException e) {
        log.error("参数错误", e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        CommonResult<Void> commonResult = new CommonResult<>(message, e);
        return commonResult;
    }


    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(DecodeException.class)
    public CommonResult<Void> decodeException(DecodeException ex){
        log.error("解码失败: {}", ex.getMessage());
        if(ex.getCause() instanceof CustomException){
            CustomException ce = (CustomException)ex.getCause();
            String message = ce.getMessage();
            CommonResult<Void> commonResult = new CommonResult<>(message, ce);
            return commonResult;
        }
        CommonResult<Void> commonResult = new CommonResult<>(ex.getMessage(), ex);
        return commonResult;
    }


}
